<template>
  <div id="message_logging">
    <div class="popover ">
      <el-popover placement="bottom" width="80" trigger="click">
        <el-button type="text" @click="systemMessages">
          系统消息
          <span :style="{ 'color': unreadMessageCount.order_num > 0 ? 'red' : '' }">
            {{ unreadMessageCount.sys_num }}
          </span>
        </el-button>
        <el-button type="text" @click="orderMessages" style="margin-left:0px;">
          订单消息<span :style="{ 'color': unreadMessageCount.order_num > 0 ? 'red' : '' }">
            {{ unreadMessageCount.order_num }}</span>
        </el-button>
        <div slot="reference" class="item">
          <el-button class="d2-mr btn-text can-hover" type="text" @click="handleClick">
            <i class="el-icon-chat-dot-square " style="font-size: 20px;font-weight: 800;"></i>
          </el-button>
          <div class="item_number">
            <span v-if="unreadMessageCount.total <= 99">{{ unreadMessageCount.total }}</span>
            <span v-else>99+</span>
          </div>
        </div>
      </el-popover>
    </div>
    <div class="MessageRemind">
      <div class="MessageRemind_item" v-for="(item, index) in messageArr" :key="index">
        <div @click="toMessageDetail(item)">{{ item.data.content.title ? item.data.content.title : '' }}</div>
        <i class="el-icon-close" @click="HandleCloseMessage(item.data.id)"></i>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {

  data() {
    return {
      messageArr: [],
      webSocket: null,
      authorization: sessionStorage.getItem('authorization'),
      url: 'ws://110.40.192.219/wss',
      hotel_id: sessionStorage.getItem('hotel_id')
      // url: 'wss://newapi.guansj.com/wss',
    }
  },
  created() {
    this.getCount()
    // this.connectWebSocket();
    this.getMessageConfig()//获取当前消息配置数据
  },
  mounted() {
    // 每隔一定时间发送ping消息
    setInterval(() => {
      // console.log('定时发送消息');
      if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
        this.sendPing();
        // console.log('定时发送消息');
        // console.log('发送消息:', this.webSocket);
      }
    }, 30000);
  },
  beforeDestroy() {
    // 关闭WebSocket连接
    if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
      this.webSocket.close();
    }
  },

  computed: {
    ...mapState('d2admin/message', [
      'messageConfig',
      'unreadMessageCount',
    ])
  },

  methods: {
    ...mapActions('d2admin/message', [
      'getMessageConfig',
      'getCount',
    ]),
    // 点击关闭信息 webSocket
    HandleCloseMessage(id) {
      this.messageArr.forEach((element, index) => {
        if (element.data.id == id) {
          this.messageArr.splice(index, 1)
        }
      });

      console.log('点击关闭信息,关闭的消息id', id);
      // console.log('剩余的消息数组', this.messageArr);

    },
    sendPing() {
      // 发送ping消息
      const data = '{"type":"ping"}';
      this.webSocket.send(data);
    },

    connectWebSocket() {
      this.webSocket = new WebSocket(`${this.url}?authorization=${this.authorization}&hotel_id=${this.hotel_id}`);
      // 监听WebSocket事件
      this.webSocket.onopen = () => {
        console.log('WebSocket连接已打开');
      };
      this.webSocket.onclose = () => {
        console.log('WebSocket连接已关闭');
        // 重新建立连接
        this.connectWebSocket();
      };
      this.webSocket.onmessage = (event) => {
        // console.log('接收到消息：', event.data);
        var message = event.data;
        var str = JSON.parse(message);
        console.log('接收到消息：', str);
        if (str.type !== 'pong') {
          this.setPushMessage(str.data.id)
          this.getCount()//获取未读消息数量
          console.log('str.type !== pong');

          if (this.messageConfig.message_volice) {
            // 声音提示
            const audio = new Audio('../../../../../public/mp3/新浪微博提示音耳聆网声音ID36702.mp3');
            audio.play(); // 播放音频
          }

          if (this.messageConfig.message_dialog) {
            // 消息弹框
            this.messageArr.push(str)
            setTimeout(() => {
              this.HandleCloseMessage(str.data.id)
            }, 180000);
          }

        }
      };
      this.webSocket.onerror = (event) => {
        console.error('WebSocket错误:', event);
      };
    },

    // 设置消息是否已推送

    setPushMessage(id) {
      let data = {
        id,
      }
      this.my_request('supplier/message/push', data, 'PUT').then(res => {
        // console.log(res, '设置消息是否已推送res',);
      })
    },

    handleClick() {
      console.log("组件点击了消息按钮");
    },
    // 跳转到消息列表
    orderMessages() {
      this.$router.push({ path: '/Messages/OrderMessages', query: { type: '2', status: '2', } })
    },
    systemMessages() {
      this.$router.push({ path: '/Messages/OrderMessages', query: { type: '1', status: '2', } })
    },



    // 跳转到消息列表并打开订单详情，
    toMessageDetail(item) {
      console.log(item, 'item');
      let id = item.data.id
      let data = item.data
      if (item.data.order_id && item.data.order_id != 0) {
        // console.log(' 订单提醒', item.data.order_id)
        this.$router.push({ path: '/Messages/OrderMessages', query: { type: '2', status: '2', data: JSON.stringify(data) } })
      } else {
        // console.log(' 新的订单', item.data.order_id)
        this.$router.push({ path: '/Messages/OrderMessages', query: { type: '1', status: '2', data: JSON.stringify(data) } })
      }
      this.HandleCloseMessage(id)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-popover .el-popper {
  text-align: center;
}

.item {
  position: relative;

  .item_number {
    position: absolute;
    top: 0;
    right: -8px;
    font-size: 11px;
    background-color: red;
    color: white;
    padding: 2px 5px;
    border-radius: 20px;
  }
}

.MessageRemind {
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 7;
  overflow: auto !important;
  width: 260px;

  .MessageRemind_item {
    width: 220px;
    min-height: 80px !important;
    height: 80px !important;
    margin-bottom: 20px;
    background-color: white;
    box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.2);
    border-left: 10px solid #0486FE;
    position: relative;
    display: flex;
    align-items: center;

    div {
      text-indent: 1em;
      font-size: 15px;
      width: 100%;
      overflow: hidden;
      height: 65px;
      line-height: 65px;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    i {
      position: absolute;
      right: 10px;
      top: 10px;
      z-index: 2;
      background-color: white;
    }
  }

}
</style>